package com.example.triprec.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.example.triprec.R;
import com.example.triprec.common.Result;
import com.example.triprec.dao.CommentDao;
import com.example.triprec.dao.TripDao;
import com.example.triprec.entity.Comment;
import com.example.triprec.entity.Trip;
import com.example.triprec.ui.adapter.TripAdapter;
import com.example.triprec.ui.dialog.CommentDialog;
import com.example.triprec.ui.dialog.EditTripDialog;
import com.example.triprec.utils.CurrentUserUtils;

import java.util.List;

public class TripFragment extends Fragment {

    private RecyclerView mRvTrips;
    private TripAdapter mTripAdapter;
    private LinearLayout mLayoutEmpty;
    private TextView mTvTabUpcoming;
    private TextView mTvTabCompleted;

    private boolean mIsShowingUpcoming = true;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_trip, container, false);
        initViews(view);
        setupListeners();
        initRecyclerView();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        loadTripData();
    }

    private void initViews(View view) {
        mRvTrips = view.findViewById(R.id.rv_trips);
        mLayoutEmpty = view.findViewById(R.id.layout_empty);
        mTvTabUpcoming = view.findViewById(R.id.tv_tab_upcoming);
        mTvTabCompleted = view.findViewById(R.id.tv_tab_completed);
    }

    private void setupListeners() {
        mTvTabUpcoming.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mIsShowingUpcoming) {
                    updateTabSelection(true);
                    loadTripData();
                }
            }
        });

        mTvTabCompleted.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mIsShowingUpcoming) {
                    updateTabSelection(false);
                    loadTripData();
                }
            }
        });
    }

    private void initRecyclerView() {
        mTripAdapter = new TripAdapter(mRvTrips);
        mTripAdapter.setOnTripClickListener(new TripAdapter.OnTripClickListener() {
            @Override
            public void onTripFinishClick(Trip trip, int position) {
                finishTrip(trip);
            }

            @Override
            public void onTripEditClick(Trip trip, int position) {
                showEditTripDialog(trip);
            }

            @Override
            public void onTripCommentClick(Trip trip, int position) {
                showAddCommentDialog(trip);
            }

            @Override
            public void onTripShowCommentClick(Trip trip, int position) {
                showCommentDialog(trip);
            }
        });
    }

    private void loadTripData() {
        try {
            // 获取当前登录用户ID
            long userId = CurrentUserUtils.getCurrentUser().getId();

            // 根据选中的标签获取数据
            Result<List<Trip>> result;
            if (mIsShowingUpcoming) {
                result = TripDao.getFutureTripsByUserId(userId);
            } else {
                result = TripDao.getCompletedTripsByUserId(userId);
            }
            updateTripList(result);
        } catch (Exception e) {
            showEmptyView();
            Toast.makeText(getContext(), "获取行程失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void updateTripList(Result<List<Trip>> result) {
        if (result.isSuccess() && result.getData() != null && !result.getData().isEmpty()) {
            mTripAdapter.setData(result.getData());
            showContentView();
        } else {
            showEmptyView();
        }
    }

    private void updateTabSelection(boolean isShowingUpcoming) {
        mIsShowingUpcoming = isShowingUpcoming;

        // 更新Tab文字样式
        mTvTabUpcoming.setTextColor(getResources().getColor(isShowingUpcoming ? R.color.primary : R.color.gray_500));
        mTvTabCompleted.setTextColor(getResources().getColor(isShowingUpcoming ? R.color.gray_500 : R.color.primary));
    }

    private void showContentView() {
        mRvTrips.setVisibility(View.VISIBLE);
        mLayoutEmpty.setVisibility(View.GONE);
    }

    private void showEmptyView() {
        mRvTrips.setVisibility(View.GONE);
        mLayoutEmpty.setVisibility(View.VISIBLE);
    }

    /**
     * 显示编辑行程对话框
     */
    private void showEditTripDialog(Trip trip) {
        EditTripDialog dialog = new EditTripDialog(getContext(), trip);
        dialog.setOnTripEditListener(new EditTripDialog.OnTripEditListener() {
            @Override
            public void onTripEditSuccess(Trip trip) {
                // 编辑成功后刷新数据
                loadTripData();
            }
        });
        dialog.show();
    }

    /**
     * 结束行程
     */
    private void finishTrip(Trip trip) {
        if (trip != null) {
            // 将行程状态设置为已完成(1)
            trip.setStatus(1);
            Result<Void> result = TripDao.updateTrip(trip);
            if (result.isSuccess()) {
                Toast.makeText(getContext(), "行程已结束", Toast.LENGTH_SHORT).show();
                loadTripData(); // 刷新数据
            } else {
                Toast.makeText(getContext(), result.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 显示添加评价对话框
     */
    private void showAddCommentDialog(Trip trip) {
        CommentDialog dialog = new CommentDialog(getContext(), trip);
        dialog.setOnCommentListener(new CommentDialog.OnCommentListener() {
            @Override
            public void onCommentSuccess(Comment comment) {
                // 评价成功后关联到行程
                trip.setComment(comment);
                // 刷新数据
                loadTripData();
            }
        });
        dialog.show();
    }

    /**
     * 显示评价详情对话框
     */
    private void showCommentDialog(Trip trip) {
        if (trip.getComment() != null) {
            // 已有评价，直接显示
            CommentDialog dialog = new CommentDialog(getContext(), trip, trip.getComment());
            dialog.show();
        } else {
            // 查询评价
            Result<Comment> result = CommentDao.getByTripId(trip.getId());
            if (result.isSuccess() && result.getData() != null) {
                // 显示评价详情
                CommentDialog dialog = new CommentDialog(getContext(), trip, result.getData());
                dialog.show();
            } else {
                // 评价不存在，显示添加评价对话框
                showAddCommentDialog(trip);
            }
        }
    }
} 